package com.ymy.thinking.in.spring.bean.definition;

import com.ymy.thinking.in.spring.bean.factory.DefaultPersonFactory;
import com.ymy.thinking.in.spring.bean.factory.PersonFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 单体 Bean 注册实例
 *
 * @author Ringo
 * @date 2021/8/27 23:11
 */
public class SingletonBeanRegistrationDemo {
    public static void main(String[] args) {
        // 创建 IoC 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 创建一个外部 PersonFactory 对象
        PersonFactory personFactory = new DefaultPersonFactory();
        SingletonBeanRegistry beanFactory = applicationContext.getBeanFactory();
        // 注册外部单例对象
        beanFactory.registerSingleton("personFactory", personFactory);
        // 开启 Spring Application Context
        applicationContext.refresh();
        // 依赖查找
        PersonFactory externalRegistryBean = applicationContext.getBean(PersonFactory.class);
        PersonFactory lookUpBean = applicationContext.getBean(PersonFactory.class);
        System.out.println(externalRegistryBean);
        System.out.println(lookUpBean);

        // 结果是 true
        System.out.println("externalRegistryBean == lookUpBean? " + (externalRegistryBean == lookUpBean));

        // 关闭 Spring Application Context
        applicationContext.close();
    }
}
